import React, { useEffect, useRef, useState } from 'react';

type RichTextEditorProps = {
    initialContent: string;
    onChange: (content: string) => void;
};

const RichTextEditor: React.FC<RichTextEditorProps> = ({ initialContent, onChange }) => {
    const editorRef = useRef<HTMLDivElement>(null);
    const [content, setContent] = useState(initialContent);

    useEffect(() => {
        if (editorRef.current && content !== editorRef.current.innerHTML) {
            editorRef.current.innerHTML = content;
        }
    }, [content]);

    useEffect(() => {
        setContent(initialContent);
    }, [initialContent]);

    const handleInput = () => {
        if (editorRef.current) {
            const newContent = editorRef.current.innerHTML;
            setContent(newContent);
            onChange(newContent);
        }
    };

    const handlePaste = (event: React.ClipboardEvent<HTMLDivElement>) => {
        event.preventDefault();
        const text = event.clipboardData.getData('text/plain');
        document.execCommand('insertText', false, text);
    };

    return (
        <div
            ref={editorRef}
            contentEditable
            onInput={handleInput}
            onPaste={handlePaste}
            className="border p-2 rounded outline-none"
            style={{ minHeight: '200px', whiteSpace: 'pre-wrap', overflowWrap: 'break-word' }}
        />
    );
};

export default RichTextEditor;
